import {
  _decorator,
  Component,
  Prefab,
  SpriteFrame,
  Node,
  EventTouch,
  instantiate,
  UITransform,
  Vec3,
  Sprite,
  Label,
} from 'cc';
import { TYPE, EventBus } from '../Utils/EventBus';
import { GameManager } from '../GameManager';

const { ccclass, property } = _decorator;

export enum CardState {
  Reday, // 可用
  Cooing, // 冷却中
  NoSun, // 阳光不足
}

@ccclass('PlantCardBase')
export default class PlantCardBase extends Component {
  @property(Prefab)
  plantPrefab: Prefab = null!; // 要种植植物的预制体

  @property
  sunCount: number = 0; // 需要的阳光

  @property
  coodown: number = 0; // 冷却时间(秒)

  coodownTimer: number = this.coodown;

  @property(SpriteFrame)
  notActiveSprite: SpriteFrame = null!; // 未激活的图层

  @property(SpriteFrame)
  activeSprite: SpriteFrame = null!; // 激活的图层

  private state: CardState = CardState.Reday;

  private _draggingNode: Node | null = null!;

  private cooling: boolean = false;

  private boundonSunChange:any

  onLoad() {
    this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
    this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
    this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
    this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    this.boundonSunChange = this.onSunChange.bind(this)
    EventBus.on(TYPE.SUN_CHANGE, this.boundonSunChange);
  }


  protected onDestroy(): void {
      EventBus.off(TYPE.SUN_CHANGE,this.boundonSunChange)
  }

  setState(state: CardState) {
    this.state = state;
    this.changeUI();
  }

  changeUI() {
    if (this.state === CardState.Cooing) {
      this.node.getComponent(Sprite).spriteFrame = this.notActiveSprite;
      this.startCoolingCountdown();
      return;
    }

    if (this.state === CardState.NoSun) {
      this.node.getComponent(Sprite).spriteFrame = this.notActiveSprite;
      return;
    }

    this.node.getComponent(Sprite).spriteFrame = this.activeSprite;
  }

  onTouchStart(event: EventTouch) {
    if (this.state !== CardState.Reday) return;
    if (this.plantPrefab) {
      this._draggingNode = instantiate(this.plantPrefab);
      this._draggingNode.setParent(
        this.node.parent.parent.getChildByName('GridLayer')
      );
      this.updateDragPosition(event);
    }
  }

  onTouchMove(event: EventTouch) {
    if (this.state !== CardState.Reday) return;
    if (this._draggingNode) {
      this.updateDragPosition(event);
    }
  }

  onTouchEnd(event: EventTouch) {
    if (this.state !== CardState.Reday) return;
    const gridLayer = this.node.parent.parent.getChildByName('GridLayer');
    if (!gridLayer) return;
    const gridTransform = gridLayer.getComponent(UITransform);
    const screenPos = event.getUILocation();
    const localPos = gridTransform.convertToNodeSpaceAR(
      new Vec3(screenPos.x, screenPos.y, 0)
    );
    EventBus.emit(TYPE.PLANT_DRAGG_END, {
      localPos,
      node: this._draggingNode,
      sun: this.sunCount,
      _this: this,
    });
  }

  updateDragPosition(event: EventTouch) {
    if (!this._draggingNode) return;

    // 先获取 GridLayer 节点
    const gridLayer = this.node.parent.parent.getChildByName('GridLayer');
    if (!gridLayer) return;

    const gridTransform = gridLayer.getComponent(UITransform)!;

    // 获取屏幕触摸位置（像素坐标）
    const screenPos = event.getUILocation();

    // 转为 GridLayer 的局部坐标
    const localPos = gridTransform.convertToNodeSpaceAR(
      new Vec3(screenPos.x, screenPos.y, 0)
    );

    // 设置拖拽节点位置
    this._draggingNode.setPosition(localPos);
  }

  onSunChange(sunCount: number) {
    if(this.state === CardState.Cooing) return
    if (sunCount >= this.sunCount) {
      this.setState(CardState.Reday);
    } else {
      this.setState(CardState.NoSun);
    }
  }

  startCoolingCountdown() {
   this.coodownTimer = this.coodown
    this.cooling = true;
    const label = this.node.getChildByName('label').getComponent(Label);
    this.schedule(() => {
      this.coodownTimer -= 1;
      label.string = this.coodownTimer + '';
      if (!this.coodownTimer) {
        this.cooling = false;
        if(GameManager._instance.sunCount >= this.sunCount) {
          this.setState(CardState.Reday)
        }else{
          this.setState(CardState.NoSun)
        }
        label.string = this.sunCount + '';
        this.coodownTimer = this.coodown;
        this.unscheduleAllCallbacks();
      }
    }, 1);
  }
}
